//
//  FlightCustomerController.m
//  ELife
//
//  Created by xiaozhi on 11-5-26.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FlightCustomerController.h"
#import "UIViewUtil.h"
#import "FlightCustomerModel.h"
#import "ELifeAppDelegate.h"
#import "EditFlightCustomerController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "GetMyData.h"
#import "LoginController.h"

@implementation FlightCustomerController
@synthesize customerTableView, _customerList;

- (void)showAlertView:(NSString *)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];
}


#pragma mark network
- (void)request:(NSDictionary*) dic withParam:(NSMutableDictionary *)param
{
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
}

// 请求登机人信息
- (void)requestCustomerList
{
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }
    
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_air_userinfo_by_user_id" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    [param setObject:userid forKey:@"user_id"];
    [param setObject:@"300" forKey:@"limit"]; // 不需要分页现实 所以limit传大一些
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
    
    [self updateView];
}

- (void)requestFinished:(NSData *)response
{
    [_customerList removeAllObjects];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    //    NSLog(@"--------body:%@", bodyElement);
    GDataXMLElement* infoElement = [[bodyElement elementsForName:@"airuserinfos"]objectAtIndex:0];
    //某个具体节点的文本内容
    NSArray* customerList = [infoElement elementsForName:@"airuserinfo"];
    NSLog(@"--------customer_list:%@", customerList);
    
    for (NSInteger index = 0; index < [customerList count]; index++) {
        GDataXMLElement *item = [customerList objectAtIndex:index];
        
        FlightCustomerModel *customerModel = [[FlightCustomerModel alloc] init];
        
        /*info_id = 登机人信息id
         user_id = 用户id
         user_name = 登机人姓名
         enger_type = 登机人类型
         certificate_type = 证件类型  （身份证/护照）
         certificate_num = 证件号码 
         insurance_number = 保险份数   1-5份   
         insurance_price = 保险金额
         phone = 登机人电话
         birthday = 登机人出生日期
         */
        
        customerModel._info_id = [[[item elementsForName:@"info_id"]objectAtIndex:0]stringValue];
        customerModel._user_id = [[[item elementsForName:@"user_id"]objectAtIndex:0]stringValue];
        customerModel._user_name = [[[item elementsForName:@"user_name"]objectAtIndex:0]stringValue];
        customerModel._enger_type = [[[item elementsForName:@"enger_type"]objectAtIndex:0]stringValue];
        customerModel._certificate_type = [[[item elementsForName:@"certificate_type"]objectAtIndex:0]stringValue];
        customerModel._certificate_num = [[[item elementsForName:@"certificate_num"]objectAtIndex:0]stringValue];
        customerModel._insurance_number = [[[item elementsForName:@"insurance_number"]objectAtIndex:0]stringValue];
        customerModel._insurance_price = [[[item elementsForName:@"insurance_price"]objectAtIndex:0]stringValue];
        customerModel._phone = [[[item elementsForName:@"phone"]objectAtIndex:0]stringValue];
        customerModel._birthday = [[[item elementsForName:@"birthday"]objectAtIndex:0]stringValue];
        
        [_customerList addObject:customerModel];
    }
    
    [doc release];
    [[ELifeAppDelegate App] hideProgressDialog];
    [customerTableView reloadData];
}



- (void)requestRemove:(FlightCustomerModel *)customerModel
{
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_delete_air_userinfo_by_info_id" forKey:@"action"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:customerModel._info_id forKey:@"info_id"];
    
     NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestRemoveFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [self request:dic withParam:param];
    
    [param release];
}

- (void)requestRemoveFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    GDataXMLElement* airuserinfosElement = [[bodyElement elementsForName:@"airuserinfos"]objectAtIndex:0];
    GDataXMLElement* airuserinfoElement = [[airuserinfosElement elementsForName:@"airuserinfo"]objectAtIndex:0];
    GDataXMLElement* retElement = [[airuserinfoElement elementsForName:@"ret"]objectAtIndex:0];
    
    // 成功
    if ([@"1" isEqualToString:[retElement stringValue]] == YES) {
        [self showAlertView:@"删除登机人成功!"];
        [self requestCustomerList];
    } else {
        [self showAlertView:@"删除登机人失败, 请稍后重试"];
    }
    

}

- (void)requestAddContact:(FlightCustomerModel *)customerModel
{
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    
    /*user_id= 用户id
    user_name= 登机人姓名
    enger_type = 登机人类型   目前只支持成人
    certificate_type = 证件类型  （身份证/护照）
    certificate_num = 证件号码 
    phone = 登机人电话
    birthday = 登机人出生日期
     */
    [param setObject:@"add_air_userinfo" forKey:@"action"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];
    [param setObject:customerModel._user_name forKey:@"user_name"];
    [param setObject:@"成人" forKey:@"enger_type"];
    [param setObject:customerModel._certificate_type forKey:@"certificate_type"];
    [param setObject:customerModel._certificate_num forKey:@"certificate_num"];
    [param setObject:customerModel._phone forKey:@"phone"];
    [param setObject:customerModel._birthday forKey:@"birthday"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestAddFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [self request:dic withParam:param];
    
    [param release];
}

- (void)requestAddFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* headElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    GDataXMLElement* returnCodeElement = [[headElement elementsForName:@"returncode"]objectAtIndex:0];
    
    // 成功
    if ([[returnCodeElement stringValue] intValue] == 0) {
        [self showAlertView:@"添加登机人成功!"];
        [self requestCustomerList];
    } else {
        [self showAlertView:@"添加登机人失败, 请稍后重试"];
    }

}

- (void)requestModifyContact:(FlightCustomerModel *)customerModel
{
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    
    /*
     user_id= 用户id                                    *******（参数必传非空）
     info_id= 登记人id                                  *******（参数必传非空）
     user_name= 登机人姓名	                           *******（参数必传可以为空）
     enger_type = 登机人类型   目前只支持成人           *******（参数必传可以为空）
     certificate_type = 证件类型  （身份证/护照）       *******（参数必传可以为空）
     certificate_num = 证件号码                         *******（参数必传可以为空）
     phone = 登机人电话                                 *******（参数必传可以为空）
     birthday = 登机人出生日期                          *******（参数必传可以为空）
     */     

    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"up_air_userinfo" forKey:@"action"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];
    [param setObject:customerModel._info_id forKey:@"info_id"];
    [param setObject:customerModel._user_name forKey:@"user_name"];
    [param setObject:customerModel._enger_type forKey:@"enger_type"];
    [param setObject:customerModel._certificate_type forKey:@"certificate_type"];
    [param setObject:customerModel._certificate_num forKey:@"certificate_num"];
    [param setObject:customerModel._phone forKey:@"phone"];
    [param setObject:customerModel._birthday forKey:@"birthday"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestModifyFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [self request:dic withParam:param];
    
    [param release];
}

- (void)requestModifyFinished:(NSData *)response
{
    [[ELifeAppDelegate App] hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* headElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    GDataXMLElement* returncodeElement = [[headElement elementsForName:@"returncode"] objectAtIndex:0];
   
    // 成功
    if ([[returncodeElement stringValue] intValue] == 0) {
        [self showAlertView:@"修改登机人成功!"];
        [self requestCustomerList];
    } else {
        [self showAlertView:@"修改登机人失败, 请稍后重试"];
//        [self.navigationController popViewControllerAnimated:YES];
    }
                                          
                                          
}

#pragma markend

- (void)dealloc
{
    [_customerList release];
    [customerTableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)updateView
{
    
    UIView *leftButton = [self.view viewWithTag:TAG_BUTTON_LEFT];
    UIView *rightButton = [self.view viewWithTag:TAG_BUTTON_RIGHT];
    UIView *noCustomerContainer = [self.view viewWithTag:TAG_NO_CUSTOMER_CONTAINER];
    
    customerTableView.hidden = YES;
    leftButton.hidden = YES;
    rightButton.hidden = YES;
    noCustomerContainer.hidden = NO;
    if ([_customerList count] > 0) {
        customerTableView.hidden = NO;
        noCustomerContainer.hidden = YES;
        leftButton.hidden = NO;
        rightButton.hidden = NO;
    }

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [customerTableView setRowHeight:111];
    
    self.view.backgroundColor = [UIViewUtil getCommonBg];
    [self updateView];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (void)fillCell:(UITableViewCell *)cell withModel:(FlightCustomerModel *)model
{
    UILabel *nameLabel = (UILabel *)[cell viewWithTag:1];
    UILabel *idCardLabel = (UILabel *)[cell viewWithTag:2];
    UILabel *priceLabel = (UILabel *)[cell viewWithTag:3];
    
    [nameLabel setText:model._user_name];
    [idCardLabel setText:model._certificate_num];
    [priceLabel setText:model._insurance_price];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    NSInteger index = indexPath.section;    
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *viewList = [[NSBundle mainBundle]loadNibNamed:@"FlightCustomerCell" owner:self options:nil];
        cell = (UITableViewCell *)[viewList objectAtIndex:0];
        
        // 设置按钮监听
        UIButton *removeButton = [cell viewWithTag:101];
        [removeButton addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
        removeButton.tag = index;
        UIButton *editButton = [cell viewWithTag:102];
        [editButton addTarget:self action:@selector(edit:) forControlEvents:UIControlEventTouchUpInside];
        editButton.tag = index;
    }
    
    [self fillCell:cell withModel:[_customerList objectAtIndex:index]];
    cell.tag = index;

    
    return cell;
}


- (void)remove:(id)sender
{
    UIButton *button = (UIButton *)sender;    
    [self requestRemove:[_customerList objectAtIndex:button.tag]];
}

- (void)edit:(id)sender
{
    UIButton *button = (UIButton *)sender;
    FlightCustomerModel *model = [_customerList objectAtIndex:button.tag];
    
    EditFlightCustomerController *nextController = [[EditFlightCustomerController alloc]initWithCustomerModel:model obj:self backAction:@selector(requestModifyContact:)];
    
    [self.navigationController pushViewController:nextController animated:YES];
    
    [nextController release];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [_customerList count];
}

#pragma mark - action

- (IBAction)addCustomer
{
    EditFlightCustomerController *nextController = [[EditFlightCustomerController alloc]initWithCustomerModel:nil obj:self backAction:@selector(requestAddContact:)];
    
    [self.navigationController pushViewController:nextController animated:YES];
    
    [nextController release];
}

// 编辑联系人
- (IBAction)editCustomer:(id)sender
{
    UIView *button = (UIView *)sender;
    NSInteger customerIndex = button.superview.tag;
    
    FlightCustomerModel *model = [_customerList objectAtIndex:customerIndex];
    
    EditFlightCustomerController *nextController = [[EditFlightCustomerController alloc]initWithCustomerModel:model obj:self backAction:@selector(requestModifyContact:)];
    
    [self.navigationController pushViewController:nextController animated:YES];
    
    [nextController release];
}

// 删除联系人
- (IBAction)removeCustomer:(id)sender
{
    UIView *button = (UIView *)sender;
    NSInteger customerIndex = button.superview.tag;
    [self requestRemove:[_customerList objectAtIndex:customerIndex]];
}

// 返回
- (IBAction)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma markend

@end
